// pages/marketCenter2/boughtOrSoldGoods/boughtOrSoldGoods.js
const app = getApp()
import api from '../../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //等待框
    waitHidden: false,
    goodsItemList: [],
    navBarHeight: 88, //导航栏高度
    menuBotton: app.globalData.menuBotton, //导航栏距离顶部距离
    menuHeight: app.globalData.menuHeight, //导航栏高度
    //页面尺寸数据
    windowHeight: 0,
    screenHeight: 0,
    currentData: 0, //当前页面：0为我求购的，1为我拍下的
    height: 1624,
    userId: '',
    pageIndex: 1,
    pageSize: 10,
    isRequire: true, // 区分卖出和发布
    index: 0,
    isLastPage: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    //设置屏幕尺寸数据
    this.setData({
      windowHeight: app.globalData.windowHeight,
      screenHeight: app.globalData.screenHeight,
      height: this.data.screenHeight,
      pageIndex: 1,
      isLastPage: false,
      waitHidden:false,

      // isLastPage: true,
      currentData: options.index,
      userId: wx.getStorageSync('logindata').data.id
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({
      waitHidden: false,
      goodsItemList: new Array,
    })
    
    if (that.data.currentData == 0) {
      that.requestSellGoods()
    } 
    setTimeout(function(){
      that.setData({
        waitHidden: true
      })
    },500)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    that.setData({
      pageIndex: that.data.pageIndex + 1,
      waitHidden: false
    })
    if (!that.data.isLastPage) {

      // 请求我发布的商品列表查询
      that.requestSellGoods()
    }
    that.setData({
      waitHidden: true
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  goBack: function (e) {
    wx.navigateBack({
      delta: 1,
    })
  },


  changePageTab: function (e) {
    var that = this
    if (that.data.currentData == 0 && e.detail.source == "touch") {
      that.setData({
        currentData: 1,
        waitHidden:false,
        goodsItemList: new Array,
        //清除pageNo
        pageIndex: 1,
        isLastPage: false,
        height: that.data.screenHeight, // 初始化
      })
    } else if (that.data.currentData == 1 && e.detail.source == "touch") {
      that.setData({
        currentData: 0,
        waitHidden:false,
        goodsItemList: new Array,
        //清除pageNo
        pageIndex: 1,
        isLastPage: false,
        height: that.data.screenHeight, // 初始化
      })
    }

    
    if (that.data.currentData == "0") { // 我发布的页面
      that.requestSellGoods()
    } else if (that.data.currentData == "1") { // 我拍下的页面
      that.requestBookedGoods()
    }
    setTimeout(function(){
      that.setData({
        waitHidden:true
      })
    },1000)
  },

  /**
   * 点击切换，滑块index赋值，切换“我求购的”与“我拍下的”
   */
  swichNav1: function (e) {
    var that = this;
    if (that.data.currentData == e.currentTarget.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.currentTarget.dataset.current,
        currentTab: e.currentTarget.dataset.current == 0 ? 0 : 1,
        goodsItemList: new Array,
        //清除pageNo
        pageIndex: 1,
        isLastPage: false,
        height: that.data.screenHeight, // 初始化
        scrollLeft: 0,
        waitHidden:false
      })
    }
  },

  // 请求我拍下的商品
  requestBookedGoods: function () {
    var that = this
    //请求已拍下
    wx.request({
      url: api.getBookedGoods + "?pageSize=999",
      method: "GET",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success(res) {
        if(res.data.data.total > 0 ) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            var index = i
            var imgUrl = res.data.data.list[i].goods.imgUrl
            var title = res.data.data.list[i].goods.title
            var price = res.data.data.list[i].goods.price
            var goodsId = res.data.data.list[i].goods.id
            var status = res.data.data.list[i].status
            var orderId = res.data.data.list[i].id
            var name = res.data.data.list[i].seller.name
            var tmp = {
              index,
              imgUrl,
              title,
              price,
              goodsId,
              status,
              name,
              orderId
            }
            that.data.goodsItemList.push(tmp)
          }
          that.setData({
            goodsItemList: that.data.goodsItemList,
            isLastPage: true
          })
  
          if (res.data.data.total > 3) {
            wx.createSelectorQuery().select('#item1 .swiper-item').boundingClientRect((rect) => {
              that.setData({
                height: 400 * (res.data.data.total + 1)
              })
            }).exec()
          } else {
            that.setData({
              height: 1624
            })
          }
        }
      }
    })
  },

  // 请求我发布的、我卖出的商品
  requestSellGoods: function () {
    var that = this
    var goodsItemListtemp = []

    wx.request({
      url: api.getMyPosts,
      data: {
        user_id: that.data.userId,
        pageSize: that.data.pageSize,
        pageIndex: that.data.pageIndex
      },
      success(res) {
        if (res.data.data.records.length != 0) {
          for (var i = 0; i < res.data.data.records.length; i++) {
            if (res.data.data.records[i].isFabu == "0") { //我卖出的
              var index = i
              var id = res.data.data.records[i].orderId // 我的发布对应goodsId，我的卖出对应订单id
              // var orderId = res.data.data.records[i].orderId
              var title = res.data.data.records[i].title
              var status = res.data.data.records[i].status
              var isRequire = true
              var bottomPrice = res.data.data.records[i].bottomPrice
              var peakPrice = res.data.data.records[i].peakPrice
              var imgUrl = res.data.data.records[i].imgUrl
              var tmp = {
                index,
                id,
                title,
                status,
                isRequire,
                bottomPrice,
                peakPrice,
                imgUrl
              }
              goodsItemListtemp.push(tmp)
            } else if (res.data.data.records[i].isFabu == "1") { //我的发布
              var index = i
              var id = res.data.data.records[i].status=="2"?res.data.data.records[i].orderId:res.data.data.records[i].id // 我的发布对应goodsId（当状态为交易中时有orderId），我的卖出对应订单id
              var title = res.data.data.records[i].title
              var status = res.data.data.records[i].status
              var price = res.data.data.records[i].bottomPrice
              var name = res.data.data.records[i].name
              var isRequire = false
              var imgUrl = res.data.data.records[i].imgUrl
              var tmp = {
                index,
                id,
                title,
                name,
                status,
                price,
                isRequire,
                imgUrl
              }
              goodsItemListtemp.push(tmp)
            }
          }
          var heightAddTotal = 0
          var heightAdd = 0
          for (var i = 0; i < goodsItemListtemp.length; i++) {
            if (goodsItemListtemp[i].status == "1" || goodsItemListtemp[i].status == "2") {
              heightAdd = 400
            } else if (goodsItemListtemp[i].status == "3" || goodsItemListtemp[i].status == "4") {
              heightAdd = 300
            }
            heightAddTotal = heightAddTotal + heightAdd
            that.data.goodsItemList.push(goodsItemListtemp[i])
          }

          that.setData({
            goodsItemList: that.data.goodsItemList,
            isLastPage: res.data.data.pageIndex >= res.data.data.totalPages
          })
          if (that.data.goodsItemList.length > 3) {
            if (res.data.data.pageIndex == 1) {
              wx.createSelectorQuery().select('#item0 .swiper-item').boundingClientRect((rect) => {
                that.setData({
                  height: heightAddTotal + 100
                })
              }).exec()
            } else {
              wx.createSelectorQuery().select('#item0 .swiper-item').boundingClientRect((rect) => {
                that.setData({
                  height: that.data.height + heightAddTotal + 100
                })
              }).exec()
            }
          
          } else {
            that.setData({
              height: that.data.screenHeight
            })
          }
        } else {
          that.setData({
            isLastPage: true
          })
        }
      }
    })
  },


  // 【我拍下的】-确认收货
  btn_confirm: function (e) {
    var that = this
    wx.request({
      url: api.goodsBuyerConfirm,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        id: that.data.goodsItemList[e.currentTarget.dataset.index].orderId
      },
      success(res) {
        if (res.data.state != 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
    setTimeout(res => {
      //刷新列表
      that.setData({
        goodsItemList: new Array,
        pageIndex: 1,
        height:that.data.screenHeight
      })
      that.requestBookedGoods()
    }, 500)
  },
  // 【我拍下的】-买家取消交易
  btn_cancel: function (e) {
    var that = this
    wx.request({
      url: api.goodsBuyerCancel,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        id: that.data.goodsItemList[e.currentTarget.dataset.index].orderId
      },
      success(res) {
        if (res.data.state != 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
    setTimeout(res => {
      //刷新列表
      that.setData({
        goodsItemList: new Array,
        pageIndex: 1,
        height:that.data.screenHeight
      })
      that.requestBookedGoods()
    }, 500)
  },


  // 【我发布的】-卖家取消交易
  btn_cancel_by_seller: function (e) {
    var that = this
    wx.request({
      url: api.goodsSellercancelOrder,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        id: that.data.goodsItemList[e.currentTarget.dataset.index].id
      },
      success(res) {
        if (res.data.state != 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
    setTimeout(res => {
      //刷新列表
      that.setData({
        goodsItemList: new Array,
        pageIndex: 1,
        height:that.data.screenHeight
      })
      that.requestSellGoods()
    }, 500)
  },

  // 【我发布的】-下架商品
  btn_remove_by_seller: function (e) {
    var that = this
    wx.request({
      url: api.goodsSellerRemove,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        id: that.data.goodsItemList[e.currentTarget.dataset.index].id
      },
      success(res) {
        if (res.data.state != 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
    setTimeout(res => {
      //刷新列表
      that.setData({
        goodsItemList: new Array,
        pageIndex: 1,
        height:that.data.screenHeight
      })
      that.requestSellGoods()
    }, 500)
  },

  // 【我卖出的】-取消交易
  cancelDeal: function (e) {
    var that = this
    wx.request({
      url: api.cancelPurchaseDeal,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        Order_id: that.data.goodsItemList[e.currentTarget.dataset.index].id, //我卖出中，id对应订单id
        User_id: that.data.userId
      },
      success(res) {
        if (res.data.state != 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
    setTimeout(res => {
      //刷新列表
      that.setData({
        goodsItemList: new Array,
        pageIndex: 1,
        height:that.data.screenHeight
      })
      that.requestSellGoods()
    }, 500)
  }
})